from django.shortcuts import render

# Create your views here.
from rest_framework.decorators import action
from rest_framework.views import APIView
from django.core.cache import cache
from rest_framework.viewsets import ViewSet, GenericViewSet
from rest_framework.mixins import CreateModelMixin

from AKapi.settings import const
from . import serializer, models
from AKapi.utils.response import APIResponse
from AKapi.libs.tx_sms import send_message, get_code
import re

from .throttlings import SMSThrottle


class LoginView(ViewSet):

    # 多方式登录接口
    @action(methods=['POST'], detail=False)
    def login(self, request, *args, **kwargs):
        ser = serializer.UserSerializer(data=request.data)
        print(ser.context)
        if ser.is_valid():
            print(ser.data)
            token = ser.context['token']
            username = ser.context['user'].username
            return APIResponse(token=token, username=username)
        else:
            return APIResponse(code=0, msg=ser.errors)

    # 手机号格式校验接口
    @action(methods=['GET'], detail=False)
    def check_telephone(self, request, *args, **kwargs):
        telephone = request.query_params.get('telephone')
        if not re.match(r'^1[3-9][0-9]{9}', telephone):
            return APIResponse(code=0, msg='手机号不合法')
        try:
            user = models.User.objects.get(telephone=telephone)
            print(user)
            return APIResponse(code=1)
        except Exception as e:
            return APIResponse(code=0, msg='手机号不存在')

    # 手机验证码登录
    @action(methods=['POST'], detail=False)
    def code_login(self, request, *args, **kwargs):
        ser = serializer.CodeUserSerializer(data=request.data)
        print(ser.is_valid())
        print(ser.errors)
        if ser.is_valid():
            token = ser.context.get('token')
            username = ser.context.get('user').username
            return APIResponse(token=token, username=username)
        else:
            return APIResponse(code=0, msg=ser.errors)


class SendSmSView(ViewSet):
    throttle_classes = [SMSThrottle]

    @action(methods=['GET'], detail=False)
    def send(self, request, *args, **kwargs):
        """
        发送验证码接口
        :return:
        """
        telephone = request.query_params.get('telephone')
        if not re.match(r'^1[3-9][0-9]{9}', telephone):
            return APIResponse(code=0, msg='手机号不合法')
        code = get_code()
        result, errmsg = send_message(telephone, code)
        # 验证码保存
        # sms_cache_%s  唯一标识
        cache.set(const.PHONE_CACHE_KEY % telephone, code, 180)
        if result:
            return APIResponse(code=1, msg='验证码发送成功', result=code)
        else:
            return APIResponse(code=0, msg=errmsg, result=code)


class RegisterView(GenericViewSet, CreateModelMixin):
    queryset = models.User.objects.all()
    serializer_class = serializer.UserRegisterSerializer

    def create(self, request, *args, **kwargs):
        response = super().create(request, *args, **kwargs)
        # ser = self.get_serializer(data=request.data)
        # ser.is_valid(raise_exception=True)
        # print(ser.data)  {'telephone': '18573778829', 'password': 'FW249746', 'username': '18573778829'}
        # print(response)
        # print(response.data)  # {'telephone': '18573778823', 'password': 'FW249746', 'username': '18573778823'}
        return APIResponse(code=1, msg='注册成功', username=response.data.get('username'))

    # 测试封装好的redis-POOL
    # def test(self):
    #     from AKapi.utils.t_redis_pool import POOL
    #     import redis
    #     conn = redis.Redis(connection_pool=POOL, decode_responses=True)
    #     ret = conn.get('name1')
